package com.updateeproject.controller;

import com.updateeproject.error.BusinessException;
import com.updateeproject.error.EmBusinessError;
import com.updateeproject.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class BaseController {
    public static final String CONTENT_TYPE_FORMED = "application/x-www-form-urlencoded";

    //定义exceptionhandler解决未被controller层吸收的exception
    //是业务逻辑的错误，并非是服务器端不能处理的错误，导致返回了500
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    //钩子***
    public Object handlerException(HttpServletRequest request, Exception ex) {

        //捕获的时候request 自动就作为实参传进来了吗？？？？？
        //传进来的异常就是上面抛出的那个异常，那异常是带有属性的（commonError）,commonError（枚举对象，EmBusiness对象）也还有属性
        //强转成(向下转型)BusinessException
        Map<String, Object> responseData = new HashMap<>();

        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            //界面空无一片，所以我们要定义我们这个要返回的object 是个什么东西
            //  put(K key, V value);
            //将errCode 和 errMsg 放到（变成）一个对象的属性
            //*** Map<String,Object> responseData = new HashMap<>();//公共代码可以提出去，简介
            responseData.put("errCode", businessException.getErrCode());
            responseData.put("errMsg", businessException.getErrMsg());
            // *** return CommonReturnType.create(responseData,"fail");
        } else {
            //***Map<String,Object> responseData = new HashMap<>();
            responseData.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrCode());
            responseData.put("errMsg", EmBusinessError.UNKNOWN_ERROR.getErrMsg());
            // ***return CommonReturnType.create(responseData,"fail");
        }
        return CommonReturnType.create(responseData, "fail");

//        CommonReturnType commonReturnType = new CommonReturnType();

//        commonReturnType.setStatus("fail");
//
//        commonReturnType.setData(responseData);
//        return commonReturnType;
/*
如果ex 不是BusinessException 该怎么处理呢
if(ex instanceof BusinessException){    才向下转型   }
 */
    }
}
